#include "stm8s.h"
#include "GPIO.h"
#include "rs485.h"
#include "TIM1_PWM.h"
#include "app_Task.h"



#define UART1_RX_IT(a)	(a?(UART1->CR2 |= (1<<5),UART1->CR2 |= (1<<2)):(UART1->CR2 &= ~(1<<5),UART1->CR2 &= ~(1<<2)))

#define countof(a)   (sizeof(a) / sizeof(*(a)))

#define HEAD_DATA	0X02
#define LAMP_CONT	4
#define HEAD_SIZE	4
#define LAMP_DATA	4
#define BUF_SIZE	HEAD_SIZE+LAMP_CONT*LAMP_DATA

uint8_t RxBuffer1[BUF_SIZE]={0};
uint8_t RxCounter1 = 0;
uint8_t full_flag = 0;


void UART_Config(void)
 {
	RS485_RX();
	CLK_PeripheralClockConfig(CLK_PERIPHERAL_UART1, ENABLE);
	/* UART1  configured as follow:
			- BaudRate = 250000 baud  
			- Word Length = 8 Bits
			- One Stop Bit
			- No parity
			- Receive and transmit enabled
	*/
	UART1_DeInit();
	UART1_Init((uint32_t)250000, UART1_WORDLENGTH_8D, UART1_STOPBITS_1, UART1_PARITY_NO,
				UART1_SYNCMODE_CLOCK_DISABLE,
			//  UART1_MODE_TXRX_ENABLE
				UART1_MODE_RX_ENABLE
				);

	/* Enable UART1 Half Duplex Mode*/
	// UART1_HalfDuplexCmd(ENABLE);//选择单线半双工模式，只在TX脚。
	
	// UART1_ITConfig(UART1_IT_RXNE_OR, DISABLE);
	UART1->CR2 |= (1<<5);//接收中断使能
	UART1->CR2 |= (1<<2);//接收使能



	UART1_Cmd(ENABLE);

	/* Enable general interrupts */
   	// enableInterrupts();
	// UART1_ReceiveData8();

}

void RS485_Receive_IRQ()
{
/* 
	if(UART1_GetFlagStatus(UART1_FLAG_RXNE))//接收非空	
	{
		UART1_ClearFlag(UART1_FLAG_RXNE);

 */
	if(UART1->SR &UART1_FLAG_RXNE)//接收非空	
	{
		UART1->SR &= ~UART1_FLAG_RXNE;
		
		if(0==full_flag)
		{

			RxBuffer1[RxCounter1++] = UART1_ReceiveData8();
			if(HEAD_DATA ==RxBuffer1[0]&&HEAD_DATA ==RxBuffer1[1]&&HEAD_DATA ==RxBuffer1[2]&&HEAD_DATA ==RxBuffer1[3])
			{
				full_flag=1;

				return;
			}

		}
		else if(1==full_flag)
		{
			RxBuffer1[RxCounter1++] = UART1_ReceiveData8();
			if((BUF_SIZE-6) == RxCounter1)
			{
				full_flag=2;
				RxCounter1=0;
				UART1_RX_IT(0);
				registeredKeysTaskID=1;
				RS485_Sendstate(1,1);
			}
		}
	}
	
}
//-----------------------------------------------------------
/* 

02 02 02 02 
64 3C 
64 64
64 64 
3C 3C 
3C 3C 
00 00 
00 00 
00 00 

02 02 02 02 
64 3C 
64 64 
64 64 
3C 3C 
3C 3C 
00 00 
00 00 
00 00 
 */



//------------------------------------------------------
	
//-------------------------------------------------------
void RS485_lamp()
{
	if(2==full_flag)
	{
		full_flag=0;
		char add=SW_coded_address();

		switch (add)
		{
		case 0x01:

			TIM1_SetCompare1(RxBuffer1[6]);
			TIM1_SetCompare2(RxBuffer1[7]);
			break;
		case 0x02:

			TIM1_SetCompare1(RxBuffer1[8]);
			TIM1_SetCompare2(RxBuffer1[9]);
			break;
		case 0x04:

			TIM1_SetCompare1(RxBuffer1[4]);
			TIM1_SetCompare2(RxBuffer1[5]);
			break;
		case 0x05:

			TIM1_SetCompare1(RxBuffer1[6]);
			TIM1_SetCompare2(RxBuffer1[7]);
			break;
		default:
			break;
		}

		for(u8 i=0;i<BUF_SIZE;i++)
		{
				RxBuffer1[i]=0;
		}
		UART1_RX_IT(1);
	}

}

//--------------------------------------
